package com.yisu.expressway.main_page;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.will.network.images.round.CircleImageView;
import com.yisu.expressway.BuildConfig;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.activity.SettingActivity;
import com.yisu.expressway.activity.UserAdviceActivity;
import com.yisu.expressway.application.ExAppLifecycle;
import com.yisu.expressway.location.LocationInfo;
import com.yisu.expressway.location.LocationListener;
import com.yisu.expressway.location.LocationService;
import com.yisu.expressway.login.LoginPageActivity;
import com.yisu.expressway.model.VersionControl;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.activity.OneDollarRecordActivity;
import com.yisu.expressway.onedollar.activity.UserAddressActivity;
import com.yisu.expressway.settings.AppConstant;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.ui.SingleButtonAlertDialog;
import com.yisu.expressway.ui.UpdateDialog;
import com.yisu.expressway.userprofile_setting.UpdateProfileEvent;
import com.yisu.expressway.userprofile_setting.UserProfileSetting;
import com.yisu.expressway.fragment.BaseFragment;
import com.yisu.expressway.model.LoginEvent;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.model.UserProfile;
import com.yisu.expressway.shopping_mall.YouZanWebActivity;
import com.yisu.expressway.ui.slideview.SlidingMenu;
import com.yisu.expressway.ui.slideview.SlidingMenuListener;
import com.yisu.expressway.ui.viewpager.SlideMenuViewPager;
import com.yisu.expressway.utils.ExAppUtils;
import com.yisu.expressway.utils.PhoneCallUtils;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;
import com.yisu.expressway.weather.WeatherActivity;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;


public class HomePageActivity extends BaseActivity implements
        ViewPager.OnPageChangeListener, SlidingMenuListener {

    private static final long PRESS_TO_QUIT_DELAY = 2000;
    @Bind(R.id.home_slide_vp)
    protected SlideMenuViewPager mSlideViewPager;
    @Bind(R.id.slide_menu)
    protected SlidingMenu mSlideMenu;
    @Bind(R.id.tb_home_indicator)
    protected ImageView mTabOneImg;
    @Bind(R.id.tb_second_indicator)
    protected ImageView mTabTwoImg;
    @Bind(R.id.tb_third_indicator)
    protected ImageView mTabThirdImg;
    @Bind(R.id.content_root)
    protected LinearLayout mContentRoot;
    @Bind(R.id.rr_titlebar)
    protected RelativeLayout mTitleBar;
    @Bind(R.id.bottom_bar)
    protected RelativeLayout mBottomBar;
    @Bind(R.id.tv_login)
    protected TextView mTvLogin;
    @Bind(R.id.iv_avatar)
    protected CircleImageView mIvAvatar;
    @Bind(R.id.user_info_header)
    protected LinearLayout mUserInfoHeader;
    @Bind(R.id.tv_title)
    protected TextView mTv_currentCity;
    @Bind(R.id.btn_tab_first)
    protected Button mTabButtonOne;
    @Bind(R.id.btn_tab_second)
    protected Button mTabButtonTwo;
    @Bind(R.id.btn_tab_third)
    protected Button mTabButtonThird;

    private long mPrePressMillis = 0;
    private int lastSelectedPos;
    private int currentSelectedPos;
    private float lastPositionOffset;
    private ImageView mLastSelectView;
    private ImageView mSelectView;

    private Button mLastHideTab;
    private Button mCurrentHideTab;
    private Animation showAnimation;
    private Animation hideAnimation;
    private int ScrollState;
    boolean bgChanged;

    private SlideViewPageAdapter mHomePagerAdapter;
    private int currentColorIndex;
    private UpdateDialog mUpdateDlg;

    private int[] contentBgColorArray = new int[3];
    private boolean tabClickByUser;
    private LocationInfo mLocationInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.activity_home_page);
        initAnimation();
        EventBus.getDefault().register(this);
        initView();
        getCurrentLocation();
        ExAppLifecycle.getIntance().setIsLaunch(true);
    }

    private void initView() {
        contentBgColorArray[0] = getResources().getColor(R.color.homeTabBlue);
        contentBgColorArray[1] = getResources().getColor(R.color.walletTabBg);
        contentBgColorArray[2] = getResources().getColor(R.color.highWayServiceTabBg);

        mSlideMenu.setSlidingMenuListener(this);

        BaseFragment[] fragmentArray = { new FragmentHome(),TabBaseFragment.newInstance(TabBaseFragment.TAB_WALLET),
                TabBaseFragment.newInstance(TabBaseFragment.TAB_SERVICE) };
        mHomePagerAdapter = new SlideViewPageAdapter(this, getSupportFragmentManager(),fragmentArray);
        mSlideViewPager.setAdapter(mHomePagerAdapter);
        mSlideViewPager.addOnPageChangeListener(this);
        mSlideViewPager.setOffscreenPageLimit(3);
//        ScrollerUtils.controlViewPagerSpeed(this, mSlideViewPager, 200);
        if(LoginManager.isLoggedIn()){
            initLoginUserInfo();
        }
        checkAppVersion();

    }

    @Override
    protected void onResume(){
        super.onResume();

    }


    @Subscribe
    public void onReceiverLoginEvent(LoginEvent event){
        if(event.getLoginResult()){
            initLoginUserInfo();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiverUpdateProfileEvent(UpdateProfileEvent event){
        if(event.getUpdateResult()){
            initLoginUserInfo();
        }
    }

    @OnClick(R.id.iv_btn_weather)
    public void jump2Weather(){
        startTargetActivity(WeatherActivity.class);
    }

    private void initLoginUserInfo(){
        UserProfile userInfo = LoginManager.getUser();
        if(userInfo != null) {
            Glide.with(getApplicationContext())
                    .load(userInfo.avatarUrl)
                    .asBitmap()
                    .placeholder(R.drawable.ic_default_avatar)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .into(mIvAvatar);
            String userName = StringUtil.isNullOrEmpty(userInfo.getUserName()) ? userInfo.userAccount : userInfo.getUserName();
            mTvLogin.setText(userName);
        }else {
            mTvLogin.setText(R.string.click_to_login);
            mIvAvatar.setImageResource(R.drawable.ic_default_avatar);
        }
    }

    @OnClick({R.id.btn_tab_first,R.id.btn_tab_second,R.id.btn_tab_third})
    public void bottomTabClick(Button button){
        int pos = 0;
        switch (button.getId()){
            case R.id.btn_tab_first:
                pos = 0;
                break;
            case R.id.btn_tab_second:
                pos = 1;
                break;
            case R.id.btn_tab_third:
                pos = 2;
                break;
            default:
                break;
        }

        tabClickByUser = true;
        mSlideViewPager.setCurrentItem(pos);

    }

    @OnClick(R.id.iv_profile)
    public void openSlideMenu() {
        mSlideMenu.toggle();
    }

    @OnClick(R.id.user_info_header)
    public void jump2profileSetting()
    {
        if(!LoginManager.isLoggedIn()) {
            startTargetActivity(LoginPageActivity.class);
        }else {
            startTargetActivity(UserProfileSetting.class);
        }

    }

    /**
     * 菜单点击入口
     * @param view TextView
     */
    @OnClick({R.id.tv_user_feedback, R.id.tv_my_order, R.id.tv_my_address,
            R.id.tv_setting,R.id.tv_contact_custom_service,R.id.tv_onedoller_record})
    public void menuOnClick(TextView view) {

        Class mTargetClass = null;

        switch (view.getId()) {
            case R.id.tv_user_feedback:
                if(LoginManager.isLoggedIn()) {
                    startTargetActivity(UserAdviceActivity.class);
                }else {
                    final MultiButtonDialog mDialog = new MultiButtonDialog(this);
                    mDialog.show();
                    mDialog.setContentText(R.string.need_to_login);
                    mDialog.setRightButtonText(R.string.click_to_login);
                    mDialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
                        @Override
                        public void onPositiveClick(String inputContent) {
                            mDialog.dismiss();
                            startTargetActivity(LoginPageActivity.class);
                        }
                    });
                }
                break;
            case R.id.tv_my_order:
                if(LoginManager.isLoggedIn()){
                    YouZanWebActivity.launch(this, BuildConfig.YOUZAN_ORDER_URL,getResources().getString(R.string.my_order));
                }else {
                    mTargetClass = LoginPageActivity.class;
                }
                break;
            case R.id.tv_my_address:
                UserAddressActivity.launch(this,UserAddressActivity.REQUEST_CODE_NORMAL,-1);
                break;
            case R.id.tv_setting:
                mTargetClass = SettingActivity.class;
                break;
            case R.id.tv_contact_custom_service:
                PhoneCallUtils.makePhoneCall(HomePageActivity.this,AppConstant.CUSTOMER_SERVICE_PHONE_NUMBER);
                break;
	        case R.id.tv_onedoller_record:
		        mTargetClass = OneDollarRecordActivity.class;
            default:
                break;
        }

        if (mTargetClass != null){
            startTargetActivity(mTargetClass);
        }
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        if(positionOffset > 0 && lastPositionOffset > 0 && ScrollState == 1){

            if(positionOffset - lastPositionOffset > 0){

                if(positionOffset > 0.5 && !bgChanged){
                    bgChanged = true;
                    int colorPos = tabClickByUser ? currentSelectedPos : lastSelectedPos + 1;
                    ContentBgColorDynamicChange(colorPos);

                }

            }else {

                if(positionOffset < 0.5 && !bgChanged){
                    bgChanged = true;
                    ContentBgColorDynamicChange(position);
                }
            }
        }

        lastPositionOffset = positionOffset;

    }

    private void ContentBgColorDynamicChange(int targetPos){

        if(targetPos > 2){
            targetPos = 2;
        }

        int startColorIndex = lastSelectedPos;
        if(currentColorIndex != currentSelectedPos){
            startColorIndex = currentColorIndex;
        }

        ValueAnimator  bgColorAnim = ObjectAnimator.ofInt(mSlideMenu,"backgroundColor",contentBgColorArray[startColorIndex],contentBgColorArray[targetPos]);
        bgColorAnim.setDuration(300);
        bgColorAnim.setEvaluator(new ArgbEvaluator());
        bgColorAnim.start();
        currentColorIndex = targetPos;

    }


    @Override
    public void onPageSelected(int position) {
        currentSelectedPos = position;
        doTabChangeAnimation(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        ScrollState = state;
        if(state == 1){
            tabClickByUser = false;
        }

        if(state == 0){
            ScrollStoped();
            bgChanged = false;
        }

    }

    /**
     * 双击退出
     *
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mPrePressMillis < PRESS_TO_QUIT_DELAY) {
                ExAppUtils.exitApp();
            } else {
                mPrePressMillis = currentTime;
                String msg = getResources().getString(R.string.press_again_to_quit);
                ToastUtil.displayShortToastMsg(this, msg);
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void open() {
        mSlideViewPager.setScrollable(false);
        hideOrShowItem(false);
    }

    @Override
    public void close() {
        mSlideViewPager.setScrollable(true);
        hideOrShowItem(true);
    }

    private void initAnimation() {
        showAnimation = AnimationUtils.loadAnimation(this, R.anim.popup_show);
        showAnimation.setDuration(200);
        hideAnimation = AnimationUtils.loadAnimation(this, R.anim.popup_hide);
        hideAnimation.setDuration(200);
    }

    private void doTabChangeAnimation(int selectPos){

        mSelectView = null;
        switch (selectPos){
            case 0 :
                mSelectView = mTabOneImg;
                mCurrentHideTab = mTabButtonOne;
                break;
            case 1:
                mSelectView = mTabTwoImg;
                mCurrentHideTab = mTabButtonTwo;
                break;
            case 2:
                mSelectView = mTabThirdImg;
                mCurrentHideTab = mTabButtonThird;
                break;
            default:
                break;
        }

        if(mSelectView != null){
            mSelectView.startAnimation(showAnimation);
            mSelectView.setVisibility(View.VISIBLE);

            mCurrentHideTab.setVisibility(View.INVISIBLE);

            if(mLastSelectView == null){
                mLastSelectView = mTabOneImg;
                mLastHideTab = mTabButtonOne;
            }

            if(mLastSelectView != null) {
                mLastSelectView.startAnimation(hideAnimation);
                mLastSelectView.setVisibility(View.INVISIBLE);
                mLastSelectView = mSelectView;

                mLastHideTab.startAnimation(showAnimation);
                mLastHideTab.setVisibility(View.VISIBLE);
                mLastHideTab = mCurrentHideTab;
            }
        }

    }

    private void ScrollStoped(){
        if(!bgChanged || currentSelectedPos == lastSelectedPos) {
            ContentBgColorDynamicChange(currentSelectedPos);
        }
        lastSelectedPos = currentSelectedPos;
        currentColorIndex = currentSelectedPos;
    }

    private void hideOrShowItem(boolean isShow){
        doAlphaAnimation(mTitleBar,isShow);
        doAlphaAnimation(mBottomBar,isShow);
    }

    private void doAlphaAnimation(View targetView,boolean isShow){
        float startValue = isShow ? 0.0f : 1.0f;
        float endValue = isShow ? 1.0f : 0.0f;

        ObjectAnimator mAlphaAnim = ObjectAnimator.ofFloat(targetView,"alpha",startValue,endValue);
        mAlphaAnim.setDuration(300);
        mAlphaAnim.start();
    }


    /**
     * 检查更新
     */
    private void checkAppVersion(){
        Map<String, Object> params = new HashMap();
        params.put("platformType", 1);
        params.put("currentVersion", BuildConfig.VERSION_CODE);
        ApiClientHelper.postApi(ApiSetting.checkVersion(), new TypeToken<VersionControl>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<VersionControl>>() {
            @Override
            public void onResponse(ApiResult<VersionControl> result) {
                if (!result.success) {
                    ToastUtil.displayLongToastMsg(HomePageActivity.this, result.getMsg());
                    return;
                }


                VersionControl updateInfo = result.getResult();

                if(updateInfo == null){
                    return;
                }

                if(updateInfo.getVersionNumber() <= BuildConfig.VERSION_CODE){
                    return;
                }

                if(mUpdateDlg != null) {
                    mUpdateDlg.clean();
                    mUpdateDlg = null;
                }

                mUpdateDlg = UpdateDialog.newInstance();
                mUpdateDlg.show(HomePageActivity.this, updateInfo);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(HomePageActivity.this, volleyError.getMessage());
            }
        }, this);
    }
    /**
     * 获取当前位置
     */
    private void getCurrentLocation(){
        showLoading();
        LocationService.getInstance().start(new LocationListener() {
            @Override
            public void onSuccess(LocationInfo info) {
                mSlideMenu.closeMenu();
                mSlideMenu.setVisibility(View.VISIBLE);
                dismissLoading();
                mLocationInfo = info;
                mTv_currentCity.setText(info.getCity());
            }

            @Override
            public void onFailure(int errorCode, String errorMessage) {
                ToastUtil.displayShortToastMsg(HomePageActivity.this,errorMessage);
                mSlideMenu.closeMenu();
                mSlideMenu.setVisibility(View.VISIBLE);
                dismissLoading();
            }
        });
    }


    @Override
    protected void onDestroy(){
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
